'''last update @2025-03-03
  添加录像指定功能,复制nvram和cfg文件
  添加录像时把nvram和cfg设为只读,非录像时取消只读
  以即时存档开始录像的,只复制即时存档
'''

from datetime import datetime
import os
import shutil
import subprocess
import stat
from pathlib import Path

from mameRoms import *

### 常量定义
MAME = r'mame.exe'
#PARAMS = '-plugin autofire,inputmacro,cheat,cheatfind -window -keyboardprovider win32'
#PARAMS = '-window -console -keyboardprovider win32 -plugin inputmacro'
#PARAMS += r' -console'
#PARAMS += r' -language Chinese_Simplified -console'
PARAMS = [
  '-plugin', 'autofire,inputmacro,cheat,cheatfind',
  '-window', '-console',
  '-keyboardprovider', 'win32'
]

### 变量定义
inpText = '' # 接受输入的字符层
index = 0 # 输入编号
romName = '' # 选择的rom文件
command = '' # 命令行指令
needReplay = False # 是否录像
now = '' # 当前时间字符窜
recordFile = '' # 录像文件名,用于命令行参数
fStat = stat.S_IWRITE # 文件状态设置,根据录像需要设定为只读或非只读

## rom相关文件状态设定
def setFStat(romName, fStat):
  
  # 设定.cfg文件状态
  file_path = Path(f'cfg/{romName}.cfg').resolve()
  try:
    file_stat = os.stat(file_path)
    if fStat == ~stat.S_IWRITE:
      os.chmod(file_path, file_stat.st_mode & ~stat.S_IWRITE)
      print(f'设定{file_path}文件状态为只读')
    else:
      os.chmod(file_path, file_stat.st_mode | stat.S_IWRITE)
      print(f'{file_path}文件的只读状态清除')
  except:
    print(f'无法处理{file_path}的文件状态')
  # 设定nvram文件夹的文件状态
  try:
    folder_path = Path(f'nvram/{romName}')
    for f in folder_path.iterdir():
      if f.is_file():
        file_path = f.resolve()
        file_stat = os.stat(file_path)
        if fStat == ~stat.S_IWRITE:
          os.chmod(file_path, file_stat.st_mode & ~stat.S_IWRITE)
          print(f'设定{file_path}文件状态为只读')
        else:
          os.chmod(file_path, file_stat.st_mode | stat.S_IWRITE)
          print(f'{file_path}文件的只读状态清除')
  except:
    print(f'无法处理{folder_path.resolve()}文件夹状态')
  
  return
'''
def setFStat(romName, fStat):
  
  # 不设定的游戏,列外
  #if romName in ['s1945p']:
  #  return
  # 设定.cfg文件状态
  file_path = Path(f'cfg/{romName}.cfg').resolve()
  try:
    file_stat = os.stat(file_path)
    if fStat == stat.S_IREAD:
      os.chmod(file_path, file_stat.st_mode & fStat)
      print(f'设定{file_path}文件状态为只读')
    else:
      os.chmod(file_path, file_stat.st_mode | fStat)
      print(f'{file_path}文件的只读状态清除')
  except:
    print(f'无法处理{file_path}的文件状态')
  # 设定nvram文件夹的文件状态
  try:
    folder_path = Path(f'nvram/{romName}')
    for f in folder_path.iterdir():
      if f.is_file():
        file_path = f.resolve()
        file_stat = os.stat(file_path)
        if fStat == stat.S_IREAD:
          os.chmod(file_path, file_stat.st_mode & fStat)
          print(f'设定{file_path}文件状态为只读')
        else:
          os.chmod(file_path, file_stat.st_mode | fStat)
          print(f'{file_path}文件的只读状态清除')
  except:
    print(f'无法处理{folder_path.resolve()}文件夹状态')
  
  return
'''

### 脚本执行
print('执行MAME0.273版本:')
while((index > -1) and (index < len(ROMS))):
  ## 初始化
  needReplay = False
  now = datetime.now().strftime('%Y%m%d_%H%M%S')
  recordFile = 'temp.inp' # 默认录像文件
  fStat = stat.S_IWRITE
  print('当前时间:', now)
  ## 提示信息显示
  i = 0 # 临时变量
  while (i < len(ROMS)):
    if (i == len(ROMS)-1):
      print(f'{i+1:3} : {ROMS[i][1]:20}')
    else:
      print(f'{i+1:3} : {ROMS[i][1]:20}   {i+2:3} : {ROMS[i+1][1]:20}')
    i += 2
  ## 输入ROM编号,回车退出
  try:
    print('')
    inpText = input("输入rom编号并按回车执行,直接回车退出:")
    if (inpText in ROMS_SHOTCUT):
      romName = ROMS_SHOTCUT[inpText]
    else:
      index = int(inpText)-1
      romName = ROMS[index][0]
  except:
    exit(1)
  ## 输入录像要求,把nvram文件夹也要复制一份!
  try:
    index = int(input('需要专门录像输入1,临时录像输入2,不录像输入其他:'))
    if (index == 1):
      recordFile = romName+'_'+now+'.inp'
    if (index in [1, 2]):
      needReplay = True
      # 以存档开启录像的,复制存档到录像目录
      if romName in ROMS_STATE:
        try:
          shutil.copy2(f'sta/{romName}/9.sta', f'inp/{recordFile}.dat/9.sta')
          print(f'复制录像初始即时存档成功!')
        except:
          print(f'复制录像初始即时存档失败!')
      # 不以即时存档开始录像的,复制ctg和nvram
      else:
        setFStat(romName, stat.S_IWRITE) # 复制前取消只读,避免再次复制时被锁定
        fStat = ~stat.S_IWRITE # 录像需要设定文件状态为只读
        # 复制nvram和ctg到录像目录
        try:
          shutil.copytree(f'nvram/{romName}', f'inp/{recordFile}.dat', dirs_exist_ok=True)
          print(f'复制录像{recordFile}的nvram成功!')
        except:
          print(f'复制录像{recordFile}的nvram失败!')
        try:
          shutil.copy2(f'cfg/{romName}.cfg', f'inp/{recordFile}.dat/{romName}.cfg')
          print(f'复制录像{recordFile}的cfg成功!')
        except:
          print(f'复制录像{recordFile}的cfg失败!')
  except:
    pass
  ## 启动前设定文件状态
  setFStat(romName, fStat)
  ## 执行mame命令行
  command = [MAME, romName] + PARAMS
  # 录像
  if (needReplay):
    command += ['-record', recordFile]
  ## 启动脚本
  if romName in ROMS_BOOT:
    command += ['-autoboot_script', f'./myLua/autoboot/{romName}.lua']
  ## 开始时读档
  if romName in ROMS_STATE:
    command +=['-state', '9']
  command = ' '.join(command)
  print(command)
  ## 如果有脚本又读档,开始时把手动开启脚本的命令复制到剪贴板
  if (romName in ROMS_BOOT) and (romName in ROMS_STATE):
    text = f'game=require("{romName}")'
    subprocess.run(["clip"], input=text.encode("utf-8"), check=True)
    print(f'复制{text}到剪贴板!')
  #os.system(command)
  subprocess.run(command, shell=True)
  print('\n')
  
## 结束
exit(0)
